﻿using eslib.nnp7;
using eslib.nnp7.TCP;
using System.Net.Sockets;

namespace nnp7ChatDemo
{
    /// <summary>
    /// PayloadFFProtocol支持自定义数据包(class)
    /// 若只使用一种数据包，可使用FFProtocol<ChatPkg>
    /// </summary>
    class ChatProtocol : PayloadFFProtocol
    {
        /// <summary>
        /// 必需是已连接的(完成Connect())
        /// </summary>
        /// <param name="tcpClient"></param>
        public ChatProtocol(TcpClient tcpClient) : base(new TCPIOStream(tcpClient.GetStream()))
        {
            if (!tcpClient.Connected) throw new Exception("必需传入已完成Connect的TcpClient，应在连接完成后构造ChatProtocol");
        }

        public override void OnDisconneted()
        {
            Program.ShowSysInfo("连接已断开");
        }

        public override void OnProtocolError(string msg, Exception exception)
        {
            Console.WriteLine($"{msg}");
        }




        #region 数据包处理

        /// <summary>
        /// 处理ChatPkg聊天数据包
        /// </summary>
        /// <param name="pkg"></param>
        /// <returns></returns>
        [PayloadHandle(typeof(ChatPkg))]
        public async Task HandleChatPkg(object pkg)
        {
            Program.ShowRecvInfo($"\t{pkg}");
            await Task.CompletedTask;
        }


        /// <summary>
        /// 处理表情数据包
        /// </summary>
        /// <param name="pkg"></param>
        /// <returns></returns>
        [PayloadHandle(typeof(EmojiPkg))]
        public async Task HandleEmojiPkg(object pkg)
        {
            Program.ShowRecvInfo($"\t{pkg}");
            await Task.CompletedTask;
        }



        public override async Task DefaultHandle(object pkg)
        {
            Program.ShowSysInfo($"未进行处理的数据包:{pkg}");
            await Task.CompletedTask;
        }

        #endregion





        public async Task Chat(string msg)
        {
            //构造通讯数据包
            ChatPkg pkg = new(Name, msg);
            await SendPayload(pkg);        //发送
            Program.ShowSendInfo($"\t\t{pkg}");
        }


        public async Task Emoji(EmojiPkg.EmojiType emoji)
        {
            EmojiPkg pkg = new(emoji, Name);
            await SendPayload(pkg);
            Program.ShowSendInfo($"\t\t{pkg}");
        }


        public string Name { get; set; } = "";

    }


}
